package com.jzit168.library_base.ext

import android.view.View
import androidx.core.view.isVisible
import com.jzit168.library_base.R
import com.jzit168.library_base.databinding.RequestLayoutBinding

/**
 *@Desc:
 *@Author: Android Developer
 *@Date: 2020/10/20
 *@see show
 **/

private var failed: ((View) -> Unit)? = null

private var empty: ((View) -> Unit)? = null

/**
 * 根据不同的状态显示不同的图标和不同的文本内容
 * @param state 区分状态 [State.LOADING]加载中,[State.SUCCESS]加载成功,[State.FAILED]加载失败,[State.EMPTY]加载数据为空
 * @param msg 需要显示的提示文本
 * @see setRequestEmptyListener 设置请求状态为[State.EMPTY]的点击事件
 * @see setRequestFailedListener 设置请求状态为[State.FAILED]的点击事件
 */
fun RequestLayoutBinding.show(state: State = State.LOADING, msg: String = "") {
    this.also {
        when (state) {
            State.LOADING -> {
                it.icon.setImageResource(R.drawable.anim_loading)
                it.content.text = if (msg.isNotEmpty()) msg else "加载中..."
            }
            State.SUCCESS -> {
                root.isVisible = false
                return@also
            }
            State.FAILED -> {
                it.icon.setImageResource(R.drawable.ic_error)
                it.content.text = if (msg.isNotEmpty()) msg else "加载失败"
                it.content.setOnClickListener { v ->
                    failed?.invoke(v)
                }
            }
            State.EMPTY -> {
                it.icon.setImageResource(R.drawable.ic_empty)
                it.content.text = if (msg.isNotEmpty()) msg else "没有数据"
                it.content.setOnClickListener { v ->
                    empty?.invoke(v)
                }
            }
        }
        root.isVisible = true
    }
}

/**
 * 设置RequestLayout显示为[State.EMPTY]时的点击事件
 */
fun setRequestEmptyListener(listener: (View) -> Unit) {
    empty = listener
}

/**
 * 设置RequestLayout显示为[State.FAILED]时的点击事件
 */
fun setRequestFailedListener(listener: (View) -> Unit) {
    failed = listener
}

enum class State {
    LOADING,    //加载中
    SUCCESS,    //加载成功
    FAILED,     //加载失败
    EMPTY       //加载为空
}